<?php
/**
 * Users management following a data mapper pattern
 *
 * This file is part of Webappkit, a packages system for PHP web apps
 * @link http://webappkit.net
 * @package webappkit
 * @subpackage users
 * @author J.Ducastel <jeremie@ducastel.name>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */
class DbUsersTool extends DbMapperTool {

    static function Factory($kit_id,$cfg=array()) {
        return new DbUsersTool($kit_id,$cfg);
    }

    protected $cfg=array(
        'users'=>array(
            'class'=>'DbUser')
        ,'auth'=>array(
            'http_realm'=>null // for http authentication
            ,'salt'=>'' // for password encryption
            , 'db_sessions'=>true // if false, store user in php session data
            , 'session_key'=>'key' // db session key name (for cookie)
        )
        ,'queries'=>array(
            'get'=>"SELECT * FROM users WHERE login={'{login}'}"
            ,'session.save'=>"REPLACE INTO auth_sessions(key,user_id,start,end,ip) VALUES({'{key}'},{{user_id}},{{start}},{{end}},{'{ip}'});"));

    /**
     * @var object logged user
     */
    protected $user;

    /**
     * @var DbUserAuthSession
     */
    protected $session;

    /**
     * search user by login/pwd
     * create an auth session, set cookie
     * @param string $login user public id
     * @param string $pwd user password
     * @return object user instance
     */
    public function login($login,$pwd) {
        // search for user
        $user=$this->getByLogin($login);
        // checking pwd
        if (!$this->_checkUserPwd($user,$pwd)) {
            //throw new Exception("bad pwd",403);
            return false;
        }
        $this->user=&$user;
        // starting session
        $this->session=new DbUserAuthSession();
        $this->session->user_id=$user->id;
        //session_start();
        //$_SESSION['user']=$user; // print_r($_SESSION['user']);
        return $user;
    }

    /**
     * tries to log in an http user
     */
    public function httpLogin() {
        if (!$login=$this->_getHttpUser() or !$pwd=$this->_getHttpPwd()) {
            $realm=$this->cfg['auth']['http_realm'];
            $this->_send401Headers($realm);
            return false;
        }
        // search for user
        $user=$this->getByLogin($login);
        // checking pwd
        if (!$this->_checkUserPwd($user,$pwd)) {
            //throw new Exception("bad pwd",403);
            return false;
        }
        $this->user=&$user;
        return $user;
    }

    /**
     * search for logged user
     * search auth session cookie, then auth session
     * @return object user instance
     */
    public function loggedUser() {
        /*if (!$user=$_SESSION['user']) {
            //throw new Exception("not logged",401);
            return false;
        }*/
        return $this->user;
    }

    /**
     * get user by login
     * @access public
     * @param string $login
     */
    public function getByLogin($login) {
        return $this->get($login);
    }

    protected function _checkUserPwd($user,$pwd) {
        return $user->pwd==md5($pwd);
    }

    /**
    * sends 401 headers
    * @param string $realm http realm
    * @return bool
    */
    protected function _send401Headers($realm='Private Area') {
		header('WWW-Authenticate: Basic realm="'.$realm.'"');
		header('HTTP/1.0 401 Unauthorized');
        return true;
    }

    /**
    * return http provided user
    * @access protected
    * @return string
    */
    protected function _getHttpUser() {
		if (isset($_SERVER['PHP_AUTH_USER'])) {
			return $_SERVER['PHP_AUTH_USER'];
		} else if (isset($_SERVER['REMOTE_USER'])) {
			return $_SERVER['REMOTE_USER'];
		} else {
			return null;
		}
    }

    /**
    * return http provided pwd
    * @access protected
    * @return string
    */
    protected function _getHttpPwd() {
        return $_SERVER['PHP_AUTH_PW'];
    }
}

/**
 * auth_session table
CREATE TABLE `auth_sessions` (
`key` CHAR( 32 ) NOT NULL ,
`user_id` INT NOT NULL ,
`ip` VARCHAR( 15 ) NULL ,
`start` DATETIME NOT NULL ,
`end` DATETIME NOT NULL ,
PRIMARY KEY ( `key` )
) ENGINE = innodb;
*/
